package com.banzhi.shop.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.model.CallBack.BindWXCallBack;
import com.banzhi.shop.model.IBindWXModel;
import com.banzhi.shop.model.Impl.BindWXImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 安全中心
 */
public class SafeCenterActivity extends BaseActivity implements View.OnClickListener, Handler.Callback, BindWXCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 绑定微信
     */
    private LinearLayout ll_bindWX;
    /**
     * 修改密码
     */
    private LinearLayout ll_changepwd;
    /**
     * 绑定银行卡
     */
    private RelativeLayout rl_bandCard;

    private TextView tvname;

    private Platform plat;
    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR = 2;
    private static final int MSG_AUTH_COMPLETE = 3;
    private Handler handler;
    private IBindWXModel model;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_center);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        handler = new Handler(this);
        model = new BindWXImpl();
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        ll_bindWX = (LinearLayout) findViewById(R.id.ll_bind_WX);
        ll_changepwd = (LinearLayout) findViewById(R.id.ll_changepwd);
        rl_bandCard = (RelativeLayout) findViewById(R.id.rl_bindcard);
        tvname = (TextView) findViewById(R.id.tv_name);
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("openid_wx", ""))) {
            tvname.setText("已绑定");
        } else {
            tvname.setText("未绑定微信");
        }
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        ll_bindWX.setOnClickListener(this);
        ll_changepwd.setOnClickListener(this);
        rl_bandCard.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_bind_WX:
                if ("".equals(MyApp.loginMessage.getString("openid_wx", ""))) {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    WXLogin(Wechat.NAME);
                } else {
                    showchangebindPopupwindow();
                }
                break;
            case R.id.ll_changepwd:
                Intent intent = new Intent(this, ChangePasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_bindcard:
                Intent ABCintent = new Intent(this, AddBankCardActivity.class);
                startActivity(ABCintent);
                break;
        }
    }

    /**
     * 登录微信
     *
     * @param name
     */
    private void WXLogin(String name) {

        plat = ShareSDK.getPlatform(name);
        if (plat == null) {
            LoadingDialogUtils.dismiss();
            return;
        }

        if (plat.isAuthValid()) {
            plat.removeAccount(true);
            LoadingDialogUtils.dismiss();
            return;
        }
        if (!plat.isClientValid()) {
            ToastUtils.makeToastShort("微信未安装，请先安装微信");
            LoadingDialogUtils.dismiss();
        }
        //使用SSO授权，通过客户单授权
        plat.SSOSetting(false);
        plat.setPlatformActionListener(new PlatformActionListener() {
            public void onComplete(Platform plat, int action, HashMap<String, Object> res) {
                if (action == Platform.ACTION_USER_INFOR) {
                    LoadingDialogUtils.dismiss();
                    Message msg = new Message();
                    msg.what = MSG_AUTH_COMPLETE;
                    msg.arg2 = action;
                    msg.obj = res;
                    handler.sendMessage(msg);
                }
            }

            public void onError(Platform plat, int action, Throwable t) {
                if (action == Platform.ACTION_USER_INFOR) {
                    LoadingDialogUtils.dismiss();
                    String text = "绑定失败: " + t.getMessage();
                    ToastUtils.makeToastShort(text);
                }
                t.printStackTrace();
            }

            public void onCancel(Platform plat, int action) {
                if (action == Platform.ACTION_USER_INFOR) {
                    LoadingDialogUtils.dismiss();
                    Message msg = new Message();
                    msg.what = MSG_AUTH_CANCEL;
                    msg.arg2 = action;
                    msg.obj = plat;
                    handler.sendMessage(msg);
                }
            }
        });
        plat.showUser(null);
    }

    private String openid;

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_AUTH_CANCEL: // 取消
                ToastUtils.makeToastShort("绑定取消");
                break;
            case MSG_AUTH_ERROR:
                // 失败
                Throwable t = (Throwable) msg.obj;
                String text = "绑定失败: " + t.getMessage();
                ToastUtils.makeToastShort(text);
                t.printStackTrace();
                break;
            case MSG_AUTH_COMPLETE:
                // 成功
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                try {
                    openid = map.get("openid").toString();
                    Log.w("openid", "openid:" + openid);
//                    nickname = map.get("nickname").toString();
//                    SharedPreferences.Editor editor = MyApp.loginMessage.edit();
//                    editor.putString("nickname", nickname);
//                    editor.apply();
                    model.BindWX(openid, this);

                } catch (Exception e) {
                    ToastUtils.makeToastShort("数据异常");
                }

                break;
        }
        return false;
    }

    @Override
    public void onWXBindSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        if ("".equals(MyApp.loginMessage.getString("openid_wx", ""))) {
            editor.putString("openid_wx", "openid_wx");
            tvname.setText("已绑定");
        } else {
            editor.putString("openid_wx", "");
            tvname.setText("未绑定微信");
        }
        editor.apply();
    }

    @Override
    public void onWXBindError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
//        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
//        if ("3".equals(jsonObject.optString("code"))) {
//            showchangebindPopupwindow();
//        }
    }

    @Override
    public void onChangeWXBindSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onChangeWXBindError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 重新绑定微信提示框
     */
    private void showchangebindPopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_chang_bind_weixing, null);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        final PopupWindow popWindow = new PopupWindow(contentView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvtrue = (TextView) contentView.findViewById(R.id.tv_true);
        RelativeLayout rl = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tvtrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                model.BindWX("", SafeCenterActivity.this);
                popWindow.dismiss();
            }
        });
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
